# -*- coding: utf-8 -*-

import pandas
import requests
import re
from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D


# 爬取外汇数据
def get_data_from_sina(cut=500):
    """此方法是转为爬取来自新浪财经的数据而设计的"""
    url = "https://vip.stock.finance.sina.com.cn/forex/api/jsonp.php/var%20_DINIW2019_9_25=/NewForexService.getDayKLine?symbol=DINIW&_=2019_9_25"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"}

    response = requests.get(url=url, headers=headers)

    # print(response.text)
    '''
    var _DINIW2019_9_25=((new String("
    1985-11-08,129.2200,128.9100,129.6600,129.1300,|
    1985-11-11,129.3800,129.2200,129.4600,129.30,|
    2019-09-06,98.3769,97.9008,98.5180,97.9008,|
    2019-09-17,98.6427,98.1868,98.7450,98.2206,|
    2019-09-18,98.2181,98.1946,98.6770,98.5457,|
    2019-09-19,98.5432,98.2033,98.6249,98.3537,|
    2019-09-20,98.3508,98.1442,98.6329,98.4605,|
    2019-09-23,98.5138,98.4474,98.8407,98.6206,|
    2019-09-24,98.6232,98.2983,98.7019,98.3688,|
    2019-09-25,98.3393,98.3226,98.5849,98.5849")))    
    '''

    # string=re.findall('\((.*?)"\)"',response.text)
    # print(response.text[].replace(''))

    # 去除杂质
    newString = ''
    # shangyige = ''
    # for i in response.text:
    #     if i in '0123456789.-':
    #         newString += shangyige
    #     if i in ',':
    #         newString+='",'
    #     if i in '0123456789' and shangyige in ',':
    #         newString += '"'
    #     elif i in '0123456789' and shangyige in '|':
    #         newString+='"'
    #     shangyige=i
    # print(newString)
    for i in response.text:
        if i in '0123456789,.-|':
            newString += i
    newString = '[["' + newString.replace(',', '","').replace('","|', '"],["') + '"]]'
    newString = eval(newString)
    # print(newString)

    return newString[cut * -1:]


def show3DAaxes():
    pass
    # ax = plt.subplot(111, projection='3d')
    # ax.plot_surface(x, y, z, rstride=2, cstride=1, cmap=plt.cm.coolwarm, alpha=0.8)
    # ax.set_xlabel('x')
    # ax.set_ylabel('y')
    # ax.set_zlabel('z')
    #
    # plt.show()


def showHistogram_x_y(num):
    '展示柱状图'

    def autolabel(rects):
        for rect in rects:
            height = rect.get_height()
            plt.text(rect.get_x() + rect.get_width() / 2. - 0.2, 1.03 * height, '%s' % int(height))

    name_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']

    name_list = ['0.' + str(i + 1) for i in range(10)]
    num_list = [33, 44, 53, 16, 11, 17, 17, 10, 17, 10]
    name_list = num.keys()
    num_list = num.values()

    autolabel(plt.bar(range(len(num_list)), num_list, color='rgb', tick_label=name_list))
    plt.show()


def showHistogram_x(num):
    '一维列表的柱状图'

    def demo1(num):
        mu, sigma = 0, 1
        sampleNo = 1000
        np.random.seed(0)
        # s = np.random.normal(mu, sigma, sampleNo)

        s = num
        plt.hist(s, bins=100)  # , normed=True)
        plt.show()

    demo1(num)


def showScatter(x, y):
    x_values = range(1, 6)
    y_values = [x * x for x in x_values]
    x_values = x
    y_values = y
    '''
    scatter() 
    x:横坐标 y:纵坐标 s:点的尺寸
    '''
    plt.scatter(x_values, y_values, s=50)

    # 设置图表标题并给坐标轴加上标签
    plt.title('Square Numbers', fontsize=24)
    plt.xlabel('Value', fontsize=14)
    plt.ylabel('Square of Value', fontsize=14)

    # 设置刻度标记的大小
    plt.tick_params(axis='both', which='major', labelsize=14)
    plt.show()


def amplitude_num():
    '展示每周期的震荡幅度统计图'
    e = {}
    for i in range(15):
        e['0.' + str(i + 1)] = 0
    print(e)

    for i in get_data_from_sina():
        print(float(i[3]) - float(i[2]))
        if float(i[3]) - float(i[2]) <= 0.1:
            e['0.1'] += 1
        elif float(i[3]) - float(i[2]) <= 0.2:
            e['0.2'] += 1
        elif float(i[3]) - float(i[2]) <= 0.3:
            e['0.3'] += 1
        elif float(i[3]) - float(i[2]) <= 0.4:
            e['0.4'] += 1
        elif float(i[3]) - float(i[2]) <= 0.5:
            e['0.5'] += 1
        elif float(i[3]) - float(i[2]) <= 0.6:
            e['0.6'] += 1
        elif float(i[3]) - float(i[2]) <= 0.7:
            e['0.7'] += 1
        elif float(i[3]) - float(i[2]) <= 0.8:
            e['0.8'] += 1
        elif float(i[3]) - float(i[2]) <= 0.9:
            e['0.9'] += 1
        elif float(i[3]) - float(i[2]) <= 1.0:
            e['0.10'] += 1
        elif float(i[3]) - float(i[2]) <= 1.1:
            e['0.11'] += 1
        elif float(i[3]) - float(i[2]) <= 1.2:
            e['0.12'] += 1
        elif float(i[3]) - float(i[2]) <= 1.3:
            e['0.13'] += 1
        elif float(i[3]) - float(i[2]) <= 1.4:
            e['0.14'] += 1
        else:
            e['0.15'] += 1
    print(e)

    showHistogram_x_y(e)


def UpsAndDownsStatistics():
    "统计跌涨的数量"
    pre = []

    def previous(num):
        pre.insert(0, num)
        if len(pre) > 3:
            pre.pop()

    continuity = 0
    up = 0
    down = 0
    a, b, c, d = 0, 0, 0, 0
    for i in get_data_from_sina():
        if float(i[1]) - float(i[4]) > 0:  # 如果上涨
            up += 1
        elif float(i[1]) - float(i[4]) < 0:  # 如果下跌
            down += 1
        a, b, c, d = i, a, b, c
    print('上涨数量', up, '下降数量', down)


def Continuity():
    '连涨连跌的情况'
    """思路：
    如果之前是涨现在还涨就+
    """
    up, down = 0, 0
    a = 0
    for i in get_data_from_sina():
        if float(i[1]) - float(i[4]) > 0 and a > 0:  # 如果上涨
            up += 1
        elif float(i[1]) - float(i[4]) < 0 and a < 0:  # 如果下跌
            down += 1
        a = float(i[1]) - float(i[4])
    print(up, down)


def OpeningClosingAndHighest():
    """展示
    收盘与最高值的差
    开盘与最高值的差
    """
    open_differ = []
    close_differ = []
    for i in get_data_from_sina():
        open_differ.append(float(i[1]) - float(i[3]))
        close_differ.append(float(i[4]) - float(i[3]))

    print(open_differ, close_differ)

    x_values = open_differ
    y_values = close_differ
    '''
    scatter() 
    x:横坐标 y:纵坐标 s:点的尺寸
    '''
    plt.scatter(x_values, y_values, s=50)

    # 设置图表标题并给坐标轴加上标签
    plt.title('OpeningClosingAndHighest', fontsize=24)
    plt.xlabel('open_differ', fontsize=14)
    plt.ylabel('close_differ', fontsize=14)

    # 设置刻度标记的大小
    plt.tick_params(axis='both', which='major', labelsize=14)
    plt.show()


def OpeningClosingAndlowst():
    """展示
    收盘与最高值的差
    开盘与最高值的差
    """
    open_differ = []
    close_differ = []
    for i in get_data_from_sina():
        open_differ.append(float(i[1]) - float(i[2]))
        close_differ.append(float(i[4]) - float(i[2]))

    print(open_differ, close_differ)

    x_values = open_differ
    y_values = close_differ
    '''
    scatter() 
    x:横坐标 y:纵坐标 s:点的尺寸
    '''
    plt.scatter(x_values, y_values, s=50)

    # 设置图表标题并给坐标轴加上标签
    plt.title('OpeningClosingAndlowst', fontsize=24)
    plt.xlabel('open_differ', fontsize=14)
    plt.ylabel('close_differ', fontsize=14)

    # 设置刻度标记的大小
    plt.tick_params(axis='both', which='major', labelsize=14)
    plt.show()


def MACloseDiffer(cycle=60):
    '与均线的差值统计'
    Collection = []
    up, down = 0, 0
    data = get_data_from_sina()
    cycle = 62
    for i in range(len(data)):
        # 上一次与均线相交的记录
        if i < 16: continue
        # print(i)
        # print(data[i - 16:i])
        close = [float(j[4]) for j in data[i - 16:i]]
        # print(close)

        MA = sum(close) / len(close)
        # 当前的MA值
        # print(MA)

        # if close < MA:
        #     print("当前值小于均线的值")
        # print()

        Collection.append(close[15] - MA)

    # print(Collection)
    showHistogram_x(Collection)
    # up.append(float(i[1]) - float(i[2]))
    # down.append(float(i[4]) - float(i[2]))


def MAHighestLowestDiffer(cycle=60):
    '与均线的差值统计'
    Collection = []
    up, down = 0, 0
    data = get_data_from_sina()
    cycle = 62
    for i in range(len(data)):
        # 上一次与均线相交的记录
        if i < 16: continue
        # print(i)
        # print(data[i - 16:i])
        close = [float(j[3]) for j in data[i - 16:i]]
        close.extend([float(j[2]) for j in data[i - 16:i]])
        # print(close)

        MA = sum(close) / len(close)
        # 当前的MA值
        # print(MA)

        # if close < MA:
        #     print("当前值小于均线的值")
        # print()

        Collection.append(close[15] - MA)

    # print(Collection)
    showHistogram_x(Collection)
    # up.append(float(i[1]) - float(i[2]))
    # down.append(float(i[4]) - float(i[2]))


def MADiffer(cycle=60):
    """用来统计与上一次均线交叉的位置
    使用的是影线的数字"""

    Collection = []
    new_Collection = []
    # up, down = 0, 0
    data = get_data_from_sina()
    # cycle = 62
    old_MA = 0
    for i in range(len(data)):
        # 上一次与均线相交的记录
        if i < cycle: continue
        # print(i)
        # print(data[i - 16:i])
        close = [float(j[3]) for j in data[i - cycle:i]]
        close.extend([float(j[2]) for j in data[i - cycle:i]])
        # print(close)
        MA = sum(close) / len(close)
        if old_MA == 0:            old_MA = MA
        if float(data[i][3]) > MA and float(data[i][2]) < MA:
            Collection.append(MA)
        else:

            Collection.append(old_MA)
            old_MA = MA
        print(old_MA)

        new_Collection.append(close[cycle - 1] - old_MA)

        # 当前的MA值
        # print(MA)

        # if close < MA:
        #     print("当前值小于均线的值")
        # print()

    #     Collection.append(close[cycle-1] - MA)
    #
    # # print(Collection)
    showHistogram_x(new_Collection)
    # up.append(float(i[1]) - float(i[2]))
    # down.append(float(i[4]) - float(i[2]))


if __name__ == '__main__':
    # 开盘    最低    最高    收盘
    # get_data_from_sina()
    # showHistogram()
    # amplitude_num()
    # UpsAndDownsStatistics()
    # Continuity()
    # OpeningClosingAndHighest()
    # OpeningClosingAndlowst()
    # MAHighestLowestDiffer()
    MADiffer()
    MAHighestLowestDiffer()
